package com.zp.mall.product.service.impl;

import com.zp.common.constant.ProductConstant;
import com.zp.mall.product.dao.AttrAttrgroupRelationDao;
import com.zp.mall.product.entity.AttrAttrgroupRelationEntity;
import com.zp.mall.product.entity.AttrEntity;
import com.zp.mall.product.service.AttrAttrgroupRelationService;
import com.zp.mall.product.service.AttrService;
import com.zp.mall.product.vo.AttrGroupRelationVo;
import com.zp.mall.product.vo.AttrGroupWithAttrsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zp.common.utils.PageUtils;
import com.zp.common.utils.Query;

import com.zp.mall.product.dao.AttrGroupDao;
import com.zp.mall.product.entity.AttrGroupEntity;
import com.zp.mall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page (
                new Query<AttrGroupEntity> ().getPage (params),
                new QueryWrapper<AttrGroupEntity> ()
        );

        return new PageUtils (page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {

        IPage<AttrGroupEntity> page = null;

        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<> ();
        // key 是检索关键字
        String key = (String) params.get ("key");

        //如果 catelogId 为 0 ， 就查询所有属性分组
        if (catelogId == 0) {
            if (!StringUtils.isEmpty (key)) {
                queryWrapper.eq ("attr_group_id", key).or ().like ("attr_group_name", key);
            }
            page = this.page (
                    new Query<AttrGroupEntity> ().getPage (params), queryWrapper
            );
        } else {
            //查询三级分类下的属性分组
            queryWrapper.eq ("catelog_id", catelogId);
            if (!StringUtils.isEmpty (key)) {
                queryWrapper.and ((obj) -> {
                    obj.eq ("attr_group_id", key).or ().like ("attr_group_name", key);
                });
            }
            page = this.page (
                    new Query<AttrGroupEntity> ().getPage (params), queryWrapper
            );
        }
        return new PageUtils (page);
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> attrGroupRelationVos) {
        if (attrGroupRelationVos != null && attrGroupRelationVos.size () > 0) {
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrGroupRelationVos.stream ().map (attrGroupRelationVo -> {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity ();
                BeanUtils.copyProperties (attrGroupRelationVo, attrAttrgroupRelationEntity);
                return attrAttrgroupRelationEntity;
            }).collect (Collectors.toList ());
            // delete from pms_attr_attrgroup_relation where (attr_id = 1L and attr_group_id = 2L) OR (attr_id = 2L and attr_group_id = 3L)
            attrAttrgroupRelationDao.deleteRelation (attrAttrgroupRelationEntities);
        }

        //因为这里的删除是删除属性分组下的属性  属性分组ID是一个值
        // 所以还可以 使用  delete from pms_attr_attrgroup_relation where attr_group_id = 2L and attr_id in (1L, 2L, 3L)
    }

    /**
     * 获取属性分组没有关联的其他属性
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoAttrs(Map<String, Object> params, Long attrGroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = this.getById (attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId ();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1）、当前分类下的其它分组
        List<AttrGroupEntity> attrGroupEntities = this.list (new QueryWrapper<AttrGroupEntity> ().eq ("catelog_id", catelogId).ne ("attr_group_id", attrGroupId));
        List<Long> collect = attrGroupEntities.stream ().map (a -> {
            return a.getAttrGroupId ();
        }).collect (Collectors.toList ());
        //2.2）、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList (new QueryWrapper<AttrAttrgroupRelationEntity> ().in ("attr_group_id", collect));
        List<Long> attrIds = attrgroupRelationEntities.stream ().map (a -> {
            return a.getAttrId ();
        }).collect (Collectors.toList ());
        //2.3）、从当前分类的所有属性中移除这些属性
//        List<AttrEntity> attrEntities = attrService.list (new QueryWrapper<AttrEntity> ().eq ("catelog_id", catelogId).notIn ("attr_id", attrIds));

        //获取已经关联的属性
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList (new QueryWrapper<AttrAttrgroupRelationEntity> ().eq ("attr_group_id", attrGroupId));
        List<Long> attrIds2 = attrAttrgroupRelationEntities.stream ().map (a -> {
            return a.getAttrId ();
        }).collect (Collectors.toList ());

        attrIds.addAll (attrIds2);

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<> ();

        // 获取基本属性中 attr_id 不在 attrIds集合中的属性
        queryWrapper.eq ("attr_type", ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode ());

        if (attrIds != null && attrIds.size () > 0) {
            //从当前分类的所有属性中移除这些属性  并且 排除已经关联的属性
            queryWrapper.eq ("catelog_id", catelogId).notIn ("attr_id", attrIds);
        }

        String key = (String) params.get ("key");
        if (!StringUtils.isEmpty (key)) {
            queryWrapper.and (wrapper -> {
                wrapper.eq ("attr_id", key).or ().like ("attr_name", key);
            });
        }

        IPage<AttrEntity> page = attrService.page (
                new Query<AttrEntity> ().getPage (params),
                queryWrapper
        );

        return new PageUtils (page);
    }

    @Override
    public void addAttrRelation(List<AttrGroupRelationVo> vos) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = vos.stream ().map (v -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity ();
            BeanUtils.copyProperties (v, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect (Collectors.toList ());
        attrAttrgroupRelationService.saveBatch (attrAttrgroupRelationEntities);
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatId(Long catelogId) {
        //1、查询分组
        List<AttrGroupEntity> attrGroupEntities = this.list (new QueryWrapper<AttrGroupEntity> ().eq ("catelog_id", catelogId));

        //2、获取分组下的所有属性
        List<AttrGroupWithAttrsVo> collect = attrGroupEntities.stream ().map (attrGroupEntity -> {
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo ();
            BeanUtils.copyProperties (attrGroupEntities, vo);
            List<AttrEntity> attrs = attrService.getAttrsByAttrgroupId (vo.getAttrGroupId ());
            vo.setAttrEntities (attrs);
            return vo;
        }).collect (Collectors.toList ());

        return collect;
    }

}